package com.mornd.gulimall.search.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson.JSON;
import com.mornd.gulimall.apis.search.to.SkuEsModel;
import com.mornd.gulimall.search.constant.EsConstant;
import com.mornd.gulimall.search.entity.SearchResult;
import com.mornd.gulimall.search.service.ISearchService;
import com.mornd.gulimall.search.entity.SearchParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.lucene.search.join.ScoreMode;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.NestedQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.nested.NestedAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.nested.ParsedNested;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedLongTerms;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedStringTerms;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

import static com.mornd.gulimall.search.config.ElasticsearchConfig.COMMON_OPTIONS;
import static com.mornd.gulimall.search.constant.EsConstant.PRODUCT_PAGE_SIZE;
import static org.springframework.util.StringUtils.hasText;

/**
 * @author: mornd
 * @dateTime: 2023/8/13 - 19:48
 */
@Slf4j
@Service
public class SearchServiceImpl implements ISearchService {
    @Resource
    private RestHighLevelClient restHighLevelClient;

    // 聚合默认条数
    private static final int AGG_DEFAULT_SIZE = 100;

    @Override
    public SearchResult search(SearchParam searchParam) {
        // 动态构建查询DSL

        // 1、 准备请求
        SearchRequest searchRequest = buildSearchRequest(searchParam);
        // 返回结果
        SearchResult result = new SearchResult();

        try {
            // 2、执行请求
            SearchResponse response = restHighLevelClient.search(searchRequest, COMMON_OPTIONS);
            // 3、分析响应数据，封装统一格式返回
            result = buildSearchResult(response, searchParam);
        } catch (IOException e) {
            log.error(e.getMessage());
        }
        return result;
    }


    /**
     * 工具方法，构建查询请求
     * 模糊匹配，过滤（属性，分类，品牌，价格区间，库存），排序，分页，高亮，聚合分析
     *
     * @param searchParam
     * @return
     */
    private SearchRequest buildSearchRequest(SearchParam searchParam) {
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();

        /*
            模糊匹配，过滤（属性，分类，品牌，价格区间，库存）
         */
        // 1 构建 bool - query
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        // 1.1 must 模糊匹配
        if (hasText(searchParam.getKeyword())) {
            boolQuery.must(QueryBuilders.matchQuery("skuTitle", searchParam.getKeyword()));
        }

        // 1.2.1 bool -filter 按照3级分类id筛选
        if (searchParam.getCatalog3Id() != null) {
            boolQuery.filter(QueryBuilders.termQuery("catalogId", searchParam.getCatalog3Id()));
        }

        // 1.2.2 bool -filter 按照品牌id筛选（多个使用terms）
        if (CollUtil.isNotEmpty(searchParam.getBrandId())) {
            boolQuery.filter(QueryBuilders.termsQuery("brandId", searchParam.getBrandId()));
        }

        // 1.2.3 bool -filter 按照属性筛选
        if (CollUtil.isNotEmpty(searchParam.getAttrs())) {
            // attrs=1_5寸:6寸&attrs=2_8G:16G
            try {
                // 嵌入式 bool 查询
                for (String attrStr : searchParam.getAttrs()) {
                    BoolQueryBuilder nestedBoolQuery = QueryBuilders.boolQuery();
                    String[] s = attrStr.split("_");
                    String attrId = s[0];
                    String[] attrValues = s[1].split(":");
                    nestedBoolQuery.must(QueryBuilders.termQuery("attrs.attrId", attrId));
                    nestedBoolQuery.must(QueryBuilders.termsQuery("attrs.attrValue", attrValues));
                    // 每一个attrs条件都要生成nested查询
                    NestedQueryBuilder nestedQuery = QueryBuilders.nestedQuery("attrs", nestedBoolQuery, ScoreMode.None);
                    boolQuery.filter(nestedQuery);
                }
            } catch (Exception e) {
                log.error(e.getMessage());
            }
        }

        // 1.2.4 bool -filter 按照是否有库存筛选 0：无库存 1：有库存
        if (searchParam.getHasStock() != null) {
            boolQuery.filter(QueryBuilders.termQuery("hasStock", searchParam.getHasStock() == 1));
        }

        // 1.2.5 bool -filter 价格区间

        RangeQueryBuilder rangeQueryBuilder = QueryBuilders.rangeQuery("skuPrice");

        if (searchParam.getPriceL() != null && searchParam.getPriceR() != null && searchParam.getPriceL().compareTo(searchParam.getPriceR()) > 0) {
            searchParam.setPriceL(null);
        }

        if (searchParam.getPriceL() != null) {
            rangeQueryBuilder.gte(searchParam.getPriceL());
        }
        if (searchParam.getPriceR() != null) {
            rangeQueryBuilder.lte(searchParam.getPriceR());
        }
        boolQuery.filter(rangeQueryBuilder);


        searchSourceBuilder.query(boolQuery);

        /*
            排序，分页，高亮
         */
        // 2.1 排序
        if (hasText(searchParam.getSort())) {
            try {
                String[] split = searchParam.getSort().split("_");
                SortOrder sortOrder = "asc".equalsIgnoreCase(split[1]) ? SortOrder.ASC : SortOrder.DESC;
                searchSourceBuilder.sort(split[0], sortOrder);
            } catch (Exception e) {
                log.error(e.getMessage());
            }
        }

        // 2.2 es分页与mysql分页相同
        searchSourceBuilder.from(searchParam.getFrom().intValue());
        searchSourceBuilder.size(PRODUCT_PAGE_SIZE.intValue());

        // 2.3 高亮
        if (hasText(searchParam.getKeyword())) {
            HighlightBuilder highlight = SearchSourceBuilder.highlight();
            highlight
                    .field("skuTitle")
                    .preTags("<b style='color:red'>")
                    .postTags("</b>");
            searchSourceBuilder.highlighter(highlight);
        }

        /*
            聚合分析
         */
        // 3.1 品牌聚合
        TermsAggregationBuilder brand_agg = AggregationBuilders.terms("brand_agg")
                // 属性
                .field("brandId")
                // 查询多少条记录
                .size(AGG_DEFAULT_SIZE);
        // 品牌聚合的名称子聚合和图片子聚合，一个品牌id只对应一个品牌名称一个品牌logo，所以size=1
        brand_agg.subAggregation(AggregationBuilders.terms("brand_name_agg").field("brandName").size(1));
        brand_agg.subAggregation(AggregationBuilders.terms("brand_img_agg").field("brandImg").size(1));
        searchSourceBuilder.aggregation(brand_agg);

        // 3.2 分类聚合
        TermsAggregationBuilder catalog_agg = AggregationBuilders.terms("catalog_agg")
                .field("catalogId").size(AGG_DEFAULT_SIZE);
        // 分类聚合的子聚合
        catalog_agg.subAggregation(AggregationBuilders.terms("catalog_name_agg").field("catalogName").size(1));
        searchSourceBuilder.aggregation(catalog_agg);

        // 3.3 属性聚合 (嵌入式聚合)
        NestedAggregationBuilder attr_agg = AggregationBuilders.nested("attr_agg", "attrs");

        // attrId 子聚合
        TermsAggregationBuilder attr_id_agg = AggregationBuilders.terms("attr_id_agg").field("attrs.attrId").size(AGG_DEFAULT_SIZE);

        // attrId 下的 attrName 子聚合
        TermsAggregationBuilder attr_name_agg = AggregationBuilders.terms("attr_name_agg").field("attrs.attrName").size(1);
        // attrId 下的 attrValue 子聚合
        TermsAggregationBuilder attr_value_agg = AggregationBuilders.terms("attr_value_agg").field("attrs.attrValue").size(1);

        attr_id_agg.subAggregation(attr_name_agg);
        attr_id_agg.subAggregation(attr_value_agg);

        attr_agg.subAggregation(attr_id_agg);

        searchSourceBuilder.aggregation(attr_agg);
        // end

        System.out.println(searchSourceBuilder);

        SearchRequest searchRequest =
                new SearchRequest(new String[]{EsConstant.PRODUCT_INDEX}, searchSourceBuilder);
        return searchRequest;
    }

    /**
     * 分析结果，封装结果
     *
     * @param response
     * @param searchParam
     * @return
     */
    private SearchResult buildSearchResult(SearchResponse response, SearchParam searchParam) {
        SearchResult result = new SearchResult();

        SearchHits hits = response.getHits();

        List<SkuEsModel> products = new ArrayList<>();

        // 当前页查询到的商品
        for (SearchHit hit : hits.getHits()) {
            String sourceAsString = hit.getSourceAsString();
            SkuEsModel skuEsModel = JSON.parseObject(sourceAsString, SkuEsModel.class);
            skuEsModel.setSkuTitleText(skuEsModel.getSkuTitle());
            // 高亮信息
            Map<String, HighlightField> highlightFields = hit.getHighlightFields();
            if (CollUtil.isNotEmpty(highlightFields)) {
                HighlightField highlightField = highlightFields.get("skuTitle");
                String highlightText = highlightField.getFragments()[0].string();
                // 覆盖默认的title
                skuEsModel.setSkuTitle(highlightText);
            }

            products.add(skuEsModel);
        }

        result.setProducts(products);

        // 设置聚合信息

        // 1 分类
        List<SearchResult.CatalogVo> catalogVos = new ArrayList<>();
        // 获取名称为 catalog_agg 的 Aggregation 转为子类 ParsedLongTerms
        ParsedLongTerms catalogAgg = response.getAggregations().get("catalog_agg");
        for (Terms.Bucket bucket : catalogAgg.getBuckets()) {
            SearchResult.CatalogVo catalogVo = new SearchResult.CatalogVo();

            // key 就是分类id
            long catalogId = bucket.getKeyAsNumber().longValue();
            catalogVo.setCatalogId(catalogId);

            // 嵌套查询
            ParsedStringTerms catalogNameAgg = bucket.getAggregations().get("catalog_name_agg");
            // 一个分类对应一个分类名称，所以注解get(0)
            String catalogName = catalogNameAgg.getBuckets().get(0).getKeyAsString();
            catalogVo.setCatalogName(catalogName);

            catalogVos.add(catalogVo);
        }

        result.setCatalogs(catalogVos);

        // 2 品牌
        List<SearchResult.BrandVo> brandVos = new ArrayList<>();
        ParsedLongTerms brandAgg = response.getAggregations().get("brand_agg");
        for (Terms.Bucket bucket : brandAgg.getBuckets()) {
            SearchResult.BrandVo brandVo = new SearchResult.BrandVo();

            long brandId = bucket.getKeyAsNumber().longValue();
            brandVo.setBrandId(brandId);

            ParsedStringTerms brandNameAgg = bucket.getAggregations().get("brand_name_agg");
            String brandName = brandNameAgg.getBuckets().get(0).getKeyAsString();
            brandVo.setBrandName(brandName);

            ParsedStringTerms brandImgAgg = bucket.getAggregations().get("brand_img_agg");
            String brandImg = brandImgAgg.getBuckets().get(0).getKeyAsString();
            brandVo.setBrandImg(brandImg);

            brandVos.add(brandVo);
        }

        result.setBrands(brandVos);

        // 3 属性
        List<SearchResult.AttrVo> attrVos = new ArrayList<>();
        // 嵌套类型
        ParsedNested attrAgg = response.getAggregations().get("attr_agg");
        ParsedLongTerms attrIdAgg = attrAgg.getAggregations().get("attr_id_agg");
        for (Terms.Bucket bucket : attrIdAgg.getBuckets()) {
            SearchResult.AttrVo attrVo = new SearchResult.AttrVo();
            long attrId = bucket.getKeyAsNumber().longValue();
            // 属性id
            attrVo.setAttrId(attrId);

            // 属性名称
            ParsedStringTerms attrNameAgg = bucket.getAggregations().get("attr_name_agg");
            String attrName = attrNameAgg.getBuckets().get(0).getKeyAsString();
            attrVo.setAttrName(attrName);
            // 属性值
            ParsedStringTerms attrValueAgg = bucket.getAggregations().get("attr_value_agg");
            String attrValue = attrValueAgg.getBuckets().get(0).getKeyAsString();
            attrVo.setAttrValue(Arrays.asList(attrValue.split(",")));

            attrVos.add(attrVo);
        }
        result.setAttrs(attrVos);

        result.setKeyword(searchParam.getKeyword());
        // 当前页码
        result.setPageNum(searchParam.getPageNum());
        // 总记录数
        long total = hits.getTotalHits().value;
        result.setTotal(total);

        // 总页数
        long pages = (total % EsConstant.PRODUCT_PAGE_SIZE == 0)
                ? total / EsConstant.PRODUCT_PAGE_SIZE
                : total / EsConstant.PRODUCT_PAGE_SIZE + 1;
        result.setPages(pages);

        // 其它参数
        result.setSort(searchParam.getSort());
        result.setHasStock(searchParam.getHasStock());
        result.setCatalog3Id(searchParam.getCatalog3Id());
        if(CollUtil.isNotEmpty(searchParam.getBrandId())) {
            result.setBrandId(searchParam.getBrandId().get(0));
        }
        result.setPriceL(searchParam.getPriceL());
        result.setPriceR(searchParam.getPriceR());

        List<Integer> navs = new ArrayList<>();
        for (long i = 1; i <= pages; i++) {
            navs.add((int) i);
        }
        result.setPageNavs(navs);

        // 面包屑
        if (CollUtil.isNotEmpty(searchParam.getAttrs())) {
            List<SearchResult.NavVo> navVos = searchParam.getAttrs().stream().map(
                    item -> {
                        SearchResult.NavVo navVo = new SearchResult.NavVo();
                        try {
                            String[] split = item.split("_");
                            Long attrId = Long.valueOf(split[0]);
                            navVo.setId(attrId);
                            for (SearchResult.AttrVo attr : result.getAttrs()) {
                                if(attr.getAttrId().equals(attrId)) {
                                    navVo.setName(attr.getAttrName());
                                    break;
                                }
                            }
                            navVo.setValue(split[1]);
                        } catch (Exception e) {
                            log.error(e.getMessage());
                        }
                        return navVo;
                    }
            ).collect(Collectors.toList());
            result.setNavs(navVos);
        } else {
            result.setNavs(Collections.emptyList());
        }


        return result;
    }
}
